package com.zmj.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author zhangmj
 * @date 2018/9/24 10:41
 * BIO: 同步阻塞IO Blocking IO
 * Java 1.4以前 IO模型只支持同步阻塞IO
 */
public class BIOServer {


    public static void main(String[] args) {

    }
    public static void server1() {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream ins = null;
        OutputStream outs = null;

        try {
            serverSocket = new ServerSocket(8000);
            System.out.println("服务端启动成功，监听端口为8000，等待客户端连接...");
            socket = serverSocket.accept();
            ins = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = ins.read(buffer)) > 0){
                System.out.println(new String(buffer,0,len));
            }
            outs = socket.getOutputStream();
            outs.write("hello everybody!".getBytes());
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 采用多线程的模式去处理socket
     * 或者线程池
     */
    public static void server2() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8000);
            System.out.println("服务端启动成功，监听端口为8000，等待客户端连接...");
            while (true) {
                Socket socket = serverSocket.accept();
                // 整出一个线程，专门去处理一个操作
                new Thread(new ServerHandler(socket)).start();

            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    /**
     * 采用线程池的模式去处理socket
     */
    public static void server3() {
        ServerSocket serverSocket = null;
        ExecutorService executorService = Executors.newFixedThreadPool(60);
        try {
            serverSocket = new ServerSocket(8000);
            System.out.println("服务端启动成功，监听端口为8000，等待客户端连接...");
            while (true){
                Socket socket = serverSocket.accept();
                executorService.execute(new ServerHandler(socket));
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void server4() {
        ServerSocket serverSocket = null;
        Map<Socket,String> map = new HashMap<Socket,String>();
        try {
            serverSocket = new ServerSocket(8000);
            System.out.println("服务端启动成功，监听端口为8000，等待客户端连接...");
            while (true){
                Socket socket = serverSocket.accept();
                // 只在这里做一个登记
                map.put(socket,"Acceptable");
                // 接下来用用监听器去做一个监听
                new Thread(new ServerHandler(socket)).start();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
